<template>
  <div class="user-avatar" @click="editCropper()">
    <Avatar class="pointer" :size="props.size" :src="options.img" title="点击上传头像" round>
      点击上传
    </Avatar>
  </div>
  <client-only>
    <el-dialog :title="title"
               v-model="open"
               width="800px"
               append-to-body
               draggable
               @opened="modalOpened"
               @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :style="{height: '350px'}">
          <vue-cropper
              ref="cropper"
              :img="options.img"
              :info="true"
              :autoCrop="options.autoCrop"
              :autoCropWidth="options.autoCropWidth"
              :autoCropHeight="options.autoCropHeight"
              :fixedBox="options.fixedBox"
              :outputType="options.outputType"
              @realTime="realTime"
              v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12">
          <Image :src="previews.url" :lazy="false" style="display: flex; justify-content: center; align-items: center; max-height: 350px;"/>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12">
          <el-row>
            <el-col :xs="24" :sm="12" :md="12" :lg="11" class="mg-t-10">
              <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
                <el-button :icon="UploadFilled">选择</el-button>
              </el-upload>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" class="mg-t-10">
              <el-row :gutter="10">
                <el-col :xs="6" :sm="6" :md="6" :lg="6">
                  <el-button :icon="Plus" @click="changeScale(1)"></el-button>
                </el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="6">
                  <el-button :icon="Minus" @click="changeScale(-1)"></el-button>
                </el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="6">
                  <el-button :icon="RefreshRight" @click="rotateLeft()"></el-button>
                </el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="6">
                  <el-button :icon="RefreshLeft" @click="rotateRight()"></el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" class="mg-t-10">
          <el-row type="flex" align="middle" justify="center">
            <el-button type="primary" @click="uploadImg()">提 交</el-button>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
  </client-only>
</template>

<script setup lang="ts">
import VueCropper from "vue-cropper/next/lib/vue-cropper.vue";
import {Plus, Minus, RefreshLeft, RefreshRight, UploadFilled} from "@element-plus/icons-vue";

const props = defineProps({
  size: {
    type: Number,
    default: 100
  }
});
const emit = defineEmits(["uploadAfter"]);
const {userInfo} = useStoreToRefs(useStores.user());
const {setAvatar} = useStores.user();
const open = ref(false);
const visible = ref(false);
const title = "修改头像";
const options = reactive({
  img: userInfo.value.avatar, //裁剪图片的地址
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 200, // 默认生成截图框宽度
  autoCropHeight: 200, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: "png", // 默认生成截图为PNG格式
  filename: ''
});
const previews = ref({});
const resizeHandler = ref();
const cropper = ref();
// 编辑头像
const editCropper = () => {
  open.value = true;
}
// 打开弹出层结束时的回调
const modalOpened = () => {
  visible.value = true;
  window.addEventListener("resize", resizeHandler.value)
}
// 刷新组件
const refresh = () => {
  cropper.value.refresh();
}
// 覆盖默认的上传行为
const requestUpload = () => {
}
// 向左旋转
const rotateLeft = () => {
  cropper.value.rotateLeft();
}
// 向右旋转
const rotateRight = () => {
  cropper.value.rotateRight();
}
// 图片缩放
const changeScale = (number: number) => {
  number = number || 1;
  cropper.value.changeScale(number);
}
// 上传预处理
const beforeUpload = (file: any) => {
  if (file.type.indexOf("image/") == -1) {
    useUtils().ModalUtils.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      options.img = reader.result as string;
      options.filename = file.name;
    };
  }
}
// 上传图片
const uploadImg = () => {
  cropper.value.getCropBlob((data: any) => {
    let formData = new FormData();
    formData.append("avatarfile", data, options.filename);
    useApi().userApi.uploadAvatar(formData).then((response: any) => {
      open.value = false;
      options.img = response.data.imgUrl;
      setAvatar(response.data.imgUrl);
      useUtils().ModalUtils.msgSuccess("修改成功");
      visible.value = false;
      emit("uploadAfter");
    });
  });
}
// 实时预览
const realTime = (data: any) => {
  previews.value = data;
}
// 关闭窗口
const closeDialog = () => {
  options.img = userInfo.value.avatar;
  visible.value = false;
  window.removeEventListener("resize", resizeHandler.value)
}
</script>

<style scoped lang="scss">
.user-avatar {
  position: relative;
  display: inline-block;
  height: 100px;

  &:hover:after {
    content: '+';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 30px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    line-height: 90px;
    border-radius: 50%;
    text-align: center;
  }
}
</style>